package com.chinaunicom.system.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinaunicom.system.dto.RoleDto;
import com.chinaunicom.system.model.Menu;
import com.chinaunicom.system.model.Role;
import com.chinaunicom.system.service.IMenuService;
import com.chinaunicom.system.service.IRoleService;

@Controller
@RequestMapping("/sys/role")
public class RoleController {

	@Resource
	private IRoleService roleService;
	
	@Resource
	private IMenuService menuServcie;

	@RequestMapping("/query")
	public String query(Model model) throws Exception {
		List<Role> roles = roleService.query();
		model.addAttribute("roles", roles);
		return "/WEB-INF/system/role_list.jsp";
	}

	@RequestMapping("/queryByName")
	public String queryByName(Model model, Role role) throws Exception {
		List<Role> roles = roleService.queryByName(role.getvRolename());
		model.addAttribute("roles", roles);
		return "/WEB-INF/system/role_list.jsp";
	}

	@RequestMapping("/addData")
	public String addData(Model model) throws Exception {
		List<Menu> menu = menuServcie.query();
		model.addAttribute("menu", menu);
		return "/WEB-INF/system/role_add.jsp";

	}
	
	@RequestMapping("/save")
	public String save(RoleDto dto) throws Exception{
		roleService.save(dto);
		return "redirect:/sys/role/query";
	}
	
	/**
	 * 角色更新前的准备数据  
	 * 	1.根据id获取原来数据
	 * 	2.根据id获取角色对应的菜单编号
	 *  3.查询出所有菜单信息
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateData")
	public String updateData(Integer id,Model model) throws Exception{
		//根据id获取原来数据
		RoleDto dto = roleService.queryById(id);
		model.addAttribute("dto", dto);
		//取出角色对应的菜单信息
		List<Menu> roleMenu = dto.getMenuList();
		model.addAttribute("roleMenu", roleMenu);
		//查询出菜单所有信息
		List<Menu> menus = menuServcie.query();
		model.addAttribute("menus", menus);
		return "/WEB-INF/system/role_update.jsp";
		
	}
	
	@RequestMapping("/update")
	public String update(RoleDto dto) throws Exception{
		roleService.update(dto);
		return "redirect:/sys/role/query";
		
	}
	
	@RequestMapping("/delete")
	public String delete(Integer id) throws Exception{
		roleService.delete(id);
		return "redirect:/sys/role/query";
	}

}
